package pers.vic.sso.server.session.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import pers.vic.sso.common.model.AuthorizationCode;
import pers.vic.sso.server.config.SsoConfiguration;
import pers.vic.sso.server.session.CodeManager;
import pers.vic.sso.server.storage.StorageStrategy;

import javax.annotation.Resource;

/**
 * 描述:
 * 权码管理
 *
 * @author Vic.xu
 * @date 2021-11-01 11:35
 */
@Component
public class CodeManagerImpl implements CodeManager {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private StorageStrategy<AuthorizationCode> storageStrategy;

    @Resource
    private SsoConfiguration ssoConfiguration;

    /**
     * 授权码默过期时间 10分钟
     *
     * @return
     */
    @Override
    public int expire() {
        return ssoConfiguration.getCodeTimeout();
    }

    @Override
    public void storage(String code, AuthorizationCode authorizationCode) {
        storageStrategy.storage(cacheName(), code, authorizationCode, expire());
        logger.info("本地授权码[{}]存储成功", code);
    }

    @Override
    public AuthorizationCode validateAndRemove(String code) {
        AuthorizationCode data = storageStrategy.getData(cacheName(), code, AuthorizationCode.class);
        storageStrategy.remove(cacheName(), code, AuthorizationCode.class);
        return data;
    }

    @Override
    public String cacheName() {
        return "code";
    }
}
